package activity.login;

import android.Manifest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.itboye.hutoubenjg.R;

import java.util.Observable;
import java.util.Observer;

import activity.personal.qianbao.WebActivity;
import base.BaseActivity;
import base.MyApplcation;
import bean.login_bean.PersonDataBean;
import logincontroller.LoginController;
import logincontroller.LoginedState;
import presenter.UserPresenter;
import util.PermissionsChecker;
import util.utls.ByAlert;
import util.utls.Const;
import util.utls.IsUtilUid;
import util.utls.MyPermission;
import util.utls.SPUtils;
import util.volley.ResultEntity;

/**
 * 登录
 */
public class ActivityLogin extends BaseActivity implements Observer {
    ImageView back;// 返回图片
    EditText login_username, login_pwd;
    ToggleButton login_tb;
    TextView login_re, login_wangji;
    UserPresenter userPresenter;
    Button btnSignin;
    TextView tvTitle;
    TextView xieyi;
    private TextView tvForgetPassworld,tvReset;

    public static String LOGINEXIT = "com.itboye.ihomebank.exit";// 登录界面推出指令


    String sid;

    private PermissionsChecker mPermissionsChecker;
    private static final int REQUEST_CODE = 0; // 请求码

    public LocationClient mLocationClient = null;
    public BDLocationListener myListener = new MyLocationListener();
    private static final int BAIDU_READ_PHONE_STATE = 100;
    double dblng;
    double dblat;
    UserPresenter userPresenters;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_login);
        userPresenter = new UserPresenter(this);
        userPresenters=new UserPresenter(this);
        mLocationClient = new LocationClient(getApplicationContext());
        mLocationClient.registerLocationListener(new MyLocationListener());
//        onZhuangTaiLan();
        setStatusBarColor(R.color.main_color_two);
        tvTitle.setVisibility(View.GONE);
        // 短信登录发送过来的广播
        IntentFilter filter1 = new IntentFilter(LOGINEXIT);
        registerReceiver(emailBroadcastReceiver, filter1);
        MyPermission.CheckPermission(this,Manifest.permission.READ_PHONE_STATE);
        mPermissionsChecker = new PermissionsChecker(this);

        isCameraPermission(this,1);
        initLocation();
    }
    // 所需的全部权限
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};
    public static boolean isCameraPermission(Activity context, int requestCode){
        if (Build.VERSION.SDK_INT >= 23) {
            int aPermission = ActivityCompat.checkSelfPermission(context,Manifest.permission.READ_PHONE_STATE);
            int bPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION);
            int cPermission = ActivityCompat.checkSelfPermission(context,Manifest.permission.ACCESS_FINE_LOCATION);
            int dPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE);
            int ePermission = ActivityCompat.checkSelfPermission(context,Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (aPermission != PackageManager.PERMISSION_GRANTED || bPermission!= PackageManager.PERMISSION_GRANTED || cPermission!= PackageManager.PERMISSION_GRANTED|| dPermission!= PackageManager.PERMISSION_GRANTED|| ePermission!= PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(context, PERMISSIONS,requestCode);
                return false;
            }
        }
        return true;
    }

    BroadcastReceiver emailBroadcastReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            ActivityLogin.this.finish();
        }

        ;
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(emailBroadcastReceiver);
    }

    @Override
    protected void onInit() {

    }

    @Override
    protected void onReadIntent(Bundle bundle) {

    }

    @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 拒绝时, 关闭页面, 缺少主要权限, 无法运行
        if (requestCode == REQUEST_CODE && resultCode == PermissionsActivity.PERMISSIONS_DENIED) {
            finish();
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.xieyi://协议
                Intent intent2=new Intent(ActivityLogin.this, XieYiActivity.class);
                startActivity(intent2);
                break;
            case R.id.tvReset:
                Intent intent1=new Intent(ActivityLogin.this, WebActivity.class);
                startActivity(intent1);
                break;
            case R.id.btnSignin:
                String userName = login_username.getText().toString();
                String pwd = login_pwd.getText().toString();
                if (userName.equals("")) {
                    ByAlert.alert("请输入用户名");
                    return;
                }
                if (pwd.equals("")) {
                    ByAlert.alert("请输入密码");
                    return;
                }
                showProgressDialog("登录中,请稍后", true);
                userPresenter.login(userName, pwd);
                break;
//            case R.id.login_re:
//                intent = new Intent(LoginActivity.this, RegisterOneActivity.class);
//                startActivity(intent);
//
//                break;
//            case R.id.login_wangji:
//                intent=new Intent(LoginActivity.this,PasswordOneActivity.class);
//                startActivity(intent);
//                break;
            case R.id.login_tb:
                if (login_tb.isChecked()) {
                    login_pwd
                            .setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    login_pwd.setInputType(InputType.TYPE_CLASS_TEXT
                            | InputType.TYPE_TEXT_VARIATION_PASSWORD);

                }
                break;
            case R.id.tvForgetPassworld:
                intent=new Intent(MyApplcation.ctx,ActivityForgetPassword.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    @Override
    public void update(Observable observable, Object data) {
        ResultEntity entity = handlerError(data);
        try {
            closeProgressDialog();
        } catch (Exception e) {
        }
        if (entity != null) {
            IsUtilUid.tianjia(entity);
            if (entity.getEventType() == UserPresenter.login_success) {
                PersonDataBean bean = (PersonDataBean) entity.getData();
                if (bean != null) {

                    SPUtils.put(ActivityLogin.this, null,
                            Const.PaySecret, bean.getPaySecret());
                    SPUtils.put(ActivityLogin.this, null,
                            Const.RELE, bean.getRolesInfo().get(0).getGroupId());
                    SPUtils.put(ActivityLogin.this, null,
                            Const.ID, bean.getId());
                    SPUtils.put(ActivityLogin.this, null,
                            Const.USERNAME, bean.getUsername());
                    SPUtils.put(ActivityLogin.this, null,
                            Const.PASSWORD, bean.getPassword());
                    SPUtils.put(ActivityLogin.this, null,
                            Const.MOBILE, bean.getMobile());
                    SPUtils.put(ActivityLogin.this, null,
                            Const.IS_LOGINED, true);
                    SPUtils.put(ActivityLogin.this, null,
                            Const.HEAD, bean.getHead());
                    SPUtils.put(ActivityLogin.this, null,
                            Const.NICK, bean.getNickname());
                    SPUtils.put(ActivityLogin.this, null,
                            Const.YQM, bean.getIdcode());
                    SPUtils.put(ActivityLogin.this, null,
                            Const.ISATH, bean.getRolesInfo().get(0).getIsAuth());
                    SPUtils.put(ActivityLogin.this, null,
                            Const.S_ID, bean.getAutoLoginCode());
                    sid=bean.getAutoLoginCode();

                    LoginController.setLoginState(new LoginedState());
                    weiZhiUpdate();

                    Intent intent1 = new Intent("chaingLogin");// 更新UI
                    sendBroadcast(intent1);
                    Intent chaingLogin = new Intent("chaingLogin");// 更新HEad
                    sendBroadcast(chaingLogin);

                    Intent intent = new Intent("weixiu");
                    sendBroadcast(intent);

                    try {

                        ActivityLogin.this.finish();
                    } catch (Exception e) {
                        // TODO: handle exception
                    }
                }

            } else if (entity.getEventType() == UserPresenter.login_fail) {
                ByAlert.alert(entity.getData()+"SB");
            }
        }
    }

    /**
     * 地理位置变更
     */
    private void weiZhiUpdate(){
        userPresenters.weiZhiUpdate(IsUtilUid.isUid(),dblng+"",dblat+"",sid);
    }
    public void start(View view) {
        mLocationClient.start();
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            // requestCode即所声明的权限获取码，在checkSelfPermission时传入
            case BAIDU_READ_PHONE_STATE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获取到权限，作相应处理（调用定位SDK应当确保相关权限均被授权，否则可能引起定位失败）
                } else {
                    // 没有获取到权限，做特殊处理
                }
                break;
            default:
                break;
        }
    }
    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
        );//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        int span = 1000;
        option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(true);//可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤GPS仿真结果，默认需要
        mLocationClient.setLocOption(option);
        mLocationClient.start();
    }

    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            dblng = location.getLongitude();//纬度
            dblat = location.getLatitude();//精度
        }
    }
    public void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        mLocationClient.stop();
    }

}
